package com.sia.springcloud.protocol.config;

import com.sia.springcloud.model.Point;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobDetail;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;

import java.nio.channels.Pipe;

/**
 * @Author: Sirius
 * @Date: 2021/12/29 19:50
 * @Description: 任务触发器Trigger配置类
 **/
@Slf4j
public class TriggerConfig {

    /**
     * 根据一个JobDetail和一个点位对象初始化得到一个任务触发器Trigger
     *
     * @param point
     * @param jobDetail
     * @return 一个任务触发器
     */
    public static Trigger newTrigger(Point point, JobDetail jobDetail) {

        log.info("Trigger开始初始化：注册一个任务触发器");


        //默认数采频率为5秒一次
        Integer frequency;
        if (point.getFrequency() == null || point.getFrequency() == 0) {
            frequency = 5000;
        } else {
            frequency = point.getFrequency();
        }
        SimpleScheduleBuilder simpleScheduleBuilder = SimpleScheduleBuilder.simpleSchedule();
        simpleScheduleBuilder.withIntervalInMilliseconds(frequency);
        simpleScheduleBuilder.repeatForever();


        Trigger trigger = TriggerBuilder.newTrigger()
                .forJob(jobDetail)
                .withIdentity(String.valueOf(point.getId()))
                .withSchedule(simpleScheduleBuilder)
                .startNow()
                .build();

        return trigger;
    }
}
